package com.codechuan.demo.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.codechuan.demo.common.Constant;
import com.codechuan.demo.dto.CityInfo;
import com.codechuan.demo.dto.SuccessOrder;
import com.codechuan.demo.dto.SysUserConfig;
import com.codechuan.demo.dto.TokenObject;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.ConnectionPool;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MyHttpUtil {

    public static JSONObject login(String account, String password, String key, String type, String machineCode) {
        OkHttpClient client = new OkHttpClient();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("account", account);
        hashMap.put("password", password);
        hashMap.put("key", key);
        hashMap.put("type", type);
        hashMap.put("machineCode", machineCode);

        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, JSONObject.toJSONString(hashMap));
        // 创建请求对象，并添加自定义的请求头
        Request request = new Request.Builder()
                .url("http://" + Constant.HOST + "/hallo-api/bl/loginBl")
                .post(body)
                .build();
        // 发送请求并获取响应
        Response response = null;
        try {
            response = client.newCall(request).execute();
            // 解密原文
            String decrypt = Demo.decrypt(response.body().string());
            return JSONObject.parseObject(decrypt);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static JSONObject registerUser(String account, String password) {
        OkHttpClient client = new OkHttpClient();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("account", account);
        hashMap.put("password", password);
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, JSONObject.toJSONString(hashMap));
        // 创建请求对象，并添加自定义的请求头
        Request request = new Request.Builder()
                .url("http://" + Constant.HOST + "/hallo-api/bl/registerUser")
                .post(body)
                .build();
        // 发送请求并获取响应
        Response response = null;
        try {
            response = client.newCall(request).execute();
            // 解密原文
            String decrypt = Demo.decrypt(response.body().string());
            return JSONObject.parseObject(decrypt);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static SysUserConfig selectUserConfig() {
        OkHttpClient client = new OkHttpClient();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("account", Constant.USER_ACCOUNT);
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, JSONObject.toJSONString(hashMap));
        // 创建请求对象，并添加自定义的请求头
        Request request = new Request.Builder()
                .url("http://" + Constant.HOST + "/hallo-api/bl/selectUserConfig")
                .post(body)
                .build();
        // 发送请求并获取响应
        Response response = null;
        try {
            response = client.newCall(request).execute();
            // 解密原文
            String decrypt = Demo.decrypt(response.body().string());
            JSONObject jsonObject = JSONObject.parseObject(decrypt);
            String string = jsonObject.getString("data");
            if (string.equals("null"))
                return null;
            JSONObject jsonData = JSONObject.parseObject(string);
            SysUserConfig sysUserConfig = new SysUserConfig();
            sysUserConfig.setAccount(jsonData.getString("account"));
            sysUserConfig.setJdMs(jsonData.getString("jdMs"));
            sysUserConfig.setRsMs(jsonData.getString("rzMs"));
            sysUserConfig.setIsDw(jsonData.getString("isDw"));
            sysUserConfig.setMinMoney(jsonData.getString("minMoney"));
            sysUserConfig.setMaxMoney(jsonData.getString("maxMoney"));

            sysUserConfig.setGlqSelect(jsonData.getString("glqSelect"));
            sysUserConfig.setMin_start(jsonData.getString("minStart"));
            sysUserConfig.setPx_gz(jsonData.getString("pxGz"));

            sysUserConfig.setPc_check(jsonData.getString("pcCheck"));
            sysUserConfig.setMin_pc_number(jsonData.getString("minPcNumber"));
            sysUserConfig.setMax_pc_number(jsonData.getString("maxPcNumber"));

            sysUserConfig.setDx_check(jsonData.getString("dxCheck"));
            sysUserConfig.setMin_dx_number(jsonData.getString("minDxNumber"));
            sysUserConfig.setMax_dx_number(jsonData.getString("maxDxNumber"));

            sysUserConfig.setSs_check(jsonData.getString("ssCheck"));
            sysUserConfig.setMin_ss_number(jsonData.getString("minSsNumber"));
            sysUserConfig.setMax_ss_number(jsonData.getString("maxSsNumber"));

            sysUserConfig.setDj_check(jsonData.getString("djCheck"));
            sysUserConfig.setMin_dj_money(jsonData.getString("minDjMoney"));

            return sysUserConfig;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void getUserTokenList(String account2) {
        OkHttpClient client = new OkHttpClient();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("account", account2);
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, JSONObject.toJSONString(hashMap));
        // 创建请求对象，并添加自定义的请求头
        Request request = new Request.Builder()
                .url("http://" + Constant.HOST + "/hallo-api/bl/getUserTokenList")
                .post(body)
                .build();
        // 发送请求并获取响应
        Response response = null;
        try {
            response = client.newCall(request).execute();
            // 解密原文
            String decrypt = Demo.decrypt(response.body().string());
            JSONObject jsonObject = JSONObject.parseObject(decrypt);
            String string = jsonObject.getString("data");
            JSONObject data = JSONObject.parseObject(string);
            JSONArray tokenList = data.parseArray(data.getString("tokenList"));
            for (Object o : tokenList) {
                JSONObject listData = JSONObject.parseObject(o.toString());
                String token = listData.getString("token");
                String ticket = listData.getString("ticket");
                String desc = listData.getString("desc");
                String status = listData.getString("status");
                int errorNumber = listData.getIntValue("errorNumber");
                String type = listData.getString("type");
                String account = listData.getString("account");
                TokenObject tokenObject = new TokenObject(token, ticket, desc, status, errorNumber, type, account);
                if (account == null)
                    account = "9191";
                if (type.equals("0") && account.equals(account2)) {
                    // 封装主号信息
                    Constant.MAIN_TOKEN = token;
                    Constant.MAIN_TICKET = ticket;
                    Constant.MAIN_ERROR_NUMBER = errorNumber;
                    Constant.MAIN_ACCOUNT_STATUS = status;
                    Constant.SON_TOKENS.add(tokenObject);
                }
                if (type.equals("1")) {
                    Constant.MY_SON_TOKENS.add(tokenObject);
                    Constant.SON_TOKENS.add(tokenObject);
                    Constant.MIN_ERROR_NUMBER.put(tokenObject.getToken(), 0);
                }
            }
            // 赋值给自己的小号回显数据集合
            Constant.SON_TOKENS_SHOW = Constant.MY_SON_TOKENS;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void selectZdCsCityCode(String city) {
        OkHttpClient client = new OkHttpClient();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("cityName", city);
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, JSONObject.toJSONString(hashMap));
        // 创建请求对象，并添加自定义的请求头
        Request request = new Request.Builder()
                .url("http://" + Constant.HOST + "/hallo-api/bl/selectPcCsCityCode")
                .post(body)
                .build();
        // 发送请求并获取响应
        Response response = null;
        try {
            response = client.newCall(request).execute();
            // 解密原文
            String decrypt = Demo.decrypt(response.body().string());
            JSONObject jsonObject = JSONObject.parseObject(decrypt);
            String string = jsonObject.getString("data");
            if (string == null)
                return;
            if (string.contains(",")) {
                String[] split = string.split(",");
                for (String cityCode : split) {
                    Constant.cityCodeList.add(cityCode);
                }
            } else {
                Constant.cityCodeList.add(string);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void saveUserConfig(SysUserConfig sysUserConfig) {
        OkHttpClient client = new OkHttpClient();
        HashMap<String, Object> hashMap = new HashMap<>();

        hashMap.put("data", JSONObject.toJSONString(sysUserConfig));
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, JSONObject.toJSONString(hashMap));
        // 创建请求对象，并添加自定义的请求头
        Request request = new Request.Builder()
                .url("http://" + Constant.HOST + "/hallo-api/bl/saveUserConfig")
                .post(body)
                .build();
        // 发送请求并获取响应
        Response response = null;
        try {
            response = client.newCall(request).execute();
            // 解密原文
            String decrypt = Demo.decrypt(response.body().string());
            JSONObject jsonObject = JSONObject.parseObject(decrypt);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static boolean insertUserToken(TokenObject tokenObject) {
        OkHttpClient client = new OkHttpClient();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("token", tokenObject.getToken());
        hashMap.put("ticket", tokenObject.getTicket());
        hashMap.put("desc", tokenObject.getDesc());
        hashMap.put("status", tokenObject.getStatus());
        hashMap.put("errorNumber", tokenObject.getErrorNumber());
        hashMap.put("type", tokenObject.getType());
        hashMap.put("account", tokenObject.getAccount());
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, JSONObject.toJSONString(hashMap));
        // 创建请求对象，并添加自定义的请求头
        Request request = new Request.Builder()
                .url("http://" + Constant.HOST + "/hallo-api/bl/insertUserToken")
                .post(body)
                .build();
        // 发送请求并获取响应
        Response response = null;
        try {
            response = client.newCall(request).execute();
            // 解密原文
            String decrypt = Demo.decrypt(response.body().string());
            JSONObject jsonObject = JSONObject.parseObject(decrypt);
            if (jsonObject.getString("data").equals("1")) {
                return true;
            }
            return false;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void updateUserTokenStatus(TokenObject tokenObject) {
        OkHttpClient client = new OkHttpClient();
        HashMap<String, Object> hashMap = new HashMap<>();
        if (Constant.SON_TOKENS_SHOW.size() > 0) {
            hashMap.put("token", tokenObject.getToken());
            hashMap.put("status", tokenObject.getStatus());
        } else {
            hashMap.put("token", Constant.MAIN_TOKEN);
            hashMap.put("status", "异常");
        }
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, JSONObject.toJSONString(hashMap));
        // 创建请求对象，并添加自定义的请求头
        Request request = new Request.Builder()
                .url("http://" + Constant.HOST + "/hallo-api/bl/updateUserTokenStatus")
                .post(body)
                .build();
        // 发送请求并获取响应
        Response response = null;
        try {
            response = client.newCall(request).execute();
            // 解密原文
            String decrypt = Demo.decrypt(response.body().string());
            JSONObject jsonObject = JSONObject.parseObject(decrypt);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static boolean deleteUserMinToken(TokenObject tokenObject) {
        OkHttpClient client = new OkHttpClient();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("token", tokenObject.getToken());
        hashMap.put("account", tokenObject.getAccount());
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, JSONObject.toJSONString(hashMap));
        // 创建请求对象，并添加自定义的请求头
        Request request = new Request.Builder()
                .url("http://" + Constant.HOST + "/hallo-api/bl/deleteUserMinToken")
                .post(body)
                .build();
        // 发送请求并获取响应
        Response response = null;
        try {
            response = client.newCall(request).execute();
            // 解密原文
            String decrypt = Demo.decrypt(response.body().string());
            JSONObject jsonObject = JSONObject.parseObject(decrypt);
            if (jsonObject.getString("data").equals("1")) {
                return true;
            }
            return false;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static boolean getUserOrderList(String userAccount) {
        OkHttpClient client = new OkHttpClient();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("account", userAccount);
        hashMap.put("type", Constant.QUERY_ORDER_TYPE);
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, JSONObject.toJSONString(hashMap));
        // 创建请求对象，并添加自定义的请求头
        Request request = new Request.Builder()
                .url("http://" + Constant.HOST + "/hallo-api/bl/getUserOrderList")
                .post(body)
                .build();
        // 发送请求并获取响应
        Response response = null;
        try {
            response = client.newCall(request).execute();
            // 解密原文
            String decrypt = Demo.decrypt(response.body().string());
            JSONObject jsonObject = JSONObject.parseObject(decrypt);
            String string = jsonObject.getString("data");
            JSONObject data = JSONObject.parseObject(string);
            if (data.getString("orderList").equals("[]"))
                return false;
            JSONArray orderList = JSONObject.parseArray(data.getString("orderList"));
            if (orderList == null)
                return false;
            for (Object o : orderList) {
                JSONObject listData = JSONObject.parseObject(o.toString());
                SuccessOrder successOrder = new SuccessOrder();
                successOrder.setDriverJourneyGuid(listData.getString("driverjourneyguid"));
                successOrder.setPaxJourneyGuid(listData.getString("paxjourneyguid"));
                successOrder.setPrice(listData.getString("price"));
                successOrder.setPersonNumber(listData.getString("personnumber"));
                successOrder.setPassengerName(listData.getString("passengername"));
                successOrder.setOrderDes(listData.getString("orderdes"));
                successOrder.setCarPoolText(listData.getString("carpooltext"));
                successOrder.setMsg(listData.getString("msg"));
                successOrder.setOrderType(listData.getString("ordertype"));
                successOrder.setStartAddress(listData.getString("startaddress"));
                successOrder.setEndAddress(listData.getString("endaddress"));
                successOrder.setStartDes(listData.getString("startdes"));
                Constant.ORDER_LIST.add(successOrder);
            }
            return true;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void addUserOrder(SuccessOrder successOrder) {
        OkHttpClient client = new OkHttpClient();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("driverJourneyGuid", successOrder.getDriverJourneyGuid());
        hashMap.put("paxJourneyGuid", successOrder.getPaxJourneyGuid());
        hashMap.put("price", successOrder.getPrice());
        hashMap.put("personNumber", successOrder.getPersonNumber());
        hashMap.put("orderDes", successOrder.getOrderDes());
        hashMap.put("carPoolText", successOrder.getCarPoolText());
        hashMap.put("account", successOrder.getAccount());
        hashMap.put("msg", successOrder.getMsg());
        hashMap.put("startAddress", successOrder.getStartAddress());
        hashMap.put("endAddress", successOrder.getEndAddress());
        hashMap.put("passengerName", successOrder.getPassengerName());
        hashMap.put("orderType", successOrder.getOrderType());
        hashMap.put("startDes", successOrder.getStartDes());
        hashMap.put("account", Constant.USER_ACCOUNT);
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, JSONObject.toJSONString(hashMap));
        // 创建请求对象，并添加自定义的请求头
        Request request = new Request.Builder()
                .url("http://" + Constant.HOST + "/hallo-api/bl/addUserOrder")
                .post(body)
                .build();
        // 发送请求并获取响应
        Response response = null;
        try {
            response = client.newCall(request).execute();
            // 解密原文
            String decrypt = Demo.decrypt(response.body().string());
            JSONObject jsonObject = JSONObject.parseObject(decrypt);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static boolean deleteOrderInfo(String paxJourneyGuid) {
        OkHttpClient client = new OkHttpClient();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("paxJourneyGuid", paxJourneyGuid);
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, JSONObject.toJSONString(hashMap));
        // 创建请求对象，并添加自定义的请求头
        Request request = new Request.Builder()
                .url("http://" + Constant.HOST + "/hallo-api/bl/deleteOrderInfo")
                .post(body)
                .build();
        // 发送请求并获取响应
        Response response = null;
        try {
            response = client.newCall(request).execute();
            // 解密原文
            String decrypt = Demo.decrypt(response.body().string());
            JSONObject jsonObject = JSONObject.parseObject(decrypt);
            if (jsonObject.getString("data").equals("1")) {
                return true;
            }
            return false;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static boolean deleteAllOrderByAccount(String account) {
        OkHttpClient client = new OkHttpClient();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("account", account);
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, JSONObject.toJSONString(hashMap));
        // 创建请求对象，并添加自定义的请求头
        Request request = new Request.Builder()
                .url("http://" + Constant.HOST + "/hallo-api/bl/deleteAllOrderByAccount")
                .post(body)
                .build();
        // 发送请求并获取响应
        Response response = null;
        try {
            response = client.newCall(request).execute();
            // 解密原文
            String decrypt = Demo.decrypt(response.body().string());
            JSONObject jsonObject = JSONObject.parseObject(decrypt);
            if (jsonObject.getString("data").equals("1")) {
                return true;
            }
            return false;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param userAccount
     * @return
     * @Deprecated 解绑
     */
    public static String noBindAccount(String account) {
        OkHttpClient client = new OkHttpClient();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("account", account);
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, JSONObject.toJSONString(hashMap));
        // 创建请求对象，并添加自定义的请求头
        Request request = new Request.Builder()
                .url("http://" + Constant.HOST + "/hallo-api/bl/noBind")
                .post(body)
                .build();
        // 发送请求并获取响应
        Response response = null;
        try {
            response = client.newCall(request).execute();
            // 解密原文
            String decrypt = Demo.decrypt(response.body().string());
            JSONObject jsonObject = JSONObject.parseObject(decrypt);
            return jsonObject.getString("message");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    public static JSONObject fuck() {
        OkHttpClient client = new OkHttpClient();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("account", Constant.USER_ACCOUNT);
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, JSONObject.toJSONString(hashMap));
        // 创建请求对象，并添加自定义的请求头
        Request request = new Request.Builder()
                .url("http://" + Constant.HOST + "/hallo-api/bl/fuck")
                .post(body)
                .build();
        // 发送请求并获取响应
        Response response = null;
        try {
            response = client.newCall(request).execute();
            // 解密原文
            String decrypt = Demo.decrypt(response.body().string());
            JSONObject data = JSONObject.parseObject(decrypt);
            JSONObject object = JSONObject.parseObject(data.getString("data"));
            return object;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @param data 返回的99数据
     * @return 返回challenge
     * @Deprecated 初始化
     */
    public static HashMap<String, String> init(String data, String token, String ticket) {
        OkHttpClient client = new OkHttpClient();
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("tocken", token);
        hashMap.put("data", data);
        hashMap.put("ticket", ticket);

        String encrypt = null;

        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, JSONObject.toJSONString(hashMap));
        // 创建请求对象，并添加自定义的请求头
        Request request = new Request.Builder()
                .url("http://" + Constant.HOST + "/hallo-api/bl/init")
                .post(body)
                .build();
        // 发送请求并获取响应
        Response response = null;
        try {
            response = client.newCall(request).execute();
            // 解密原文
            String decrypt = Demo.decrypt(response.body().string());
            JSONObject jsonObject = JSONObject.parseObject(decrypt);
            String string = jsonObject.getString("data");
            JSONObject dataJson = JSONObject.parseObject(string);
            if (dataJson == null)
                return null;
            String challenge = dataJson.getString("challenge");
            String captchaId = dataJson.getString("captchaId");
            HashMap<String, String> resutMap = new HashMap<>();
            resutMap.put("challenge", challenge);
            resutMap.put("captchaId", captchaId);

            return resutMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String callBackBL(HashMap<String, String> dataMap) {
        OkHttpClient client = new OkHttpClient();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("capToken", dataMap.get("capToken"));
        hashMap.put("captchaOutput", dataMap.get("captcha_output"));
        hashMap.put("challenge", dataMap.get("challenge"));
        hashMap.put("genTime", dataMap.get("gen_time"));
        hashMap.put("lotNumber", dataMap.get("lot_number"));
        hashMap.put("passToken", dataMap.get("pass_token"));
        hashMap.put("reqId", dataMap.get("reqId"));
        hashMap.put("token", dataMap.get("capToken"));
        hashMap.put("ticket", dataMap.get("ticket"));
        MediaType mediaType = MediaType.parse("application/json");
        String encrypt;
        RequestBody body = RequestBody.create(mediaType, JSONObject.toJSONString(hashMap));
        // 创建请求对象，并添加自定义的请求头
        Request request = new Request.Builder()
                .url("http://" + Constant.HOST + "/hallo-api/bl/callBack")
                .post(body)
                .build();
        // 发送请求并获取响应
        Response response = null;
        try {
            response = client.newCall(request).execute();
            // 解密原文
            String decrypt = Demo.decrypt(response.body().string());
            JSONObject jsonObject = JSONObject.parseObject(decrypt);
            System.out.println("jsonObject = " + jsonObject);
            return "处理图形验证失败";
        } catch (Exception e) {
            configureTasks();
        }
        System.out.println("处理图形验证失败");
        return "处理图形验证失败";
    }


    /**
     * @param data 返回的99数据
     * @return 返回challenge
     * @Deprecated 初始化
     */
    public static HashMap<String, String> initSlider(String data, String token, String ticket, String sid) {
        System.out.println("初始化的sid是:" + sid);
        OkHttpClient client = new OkHttpClient();
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("capToken", token);
        hashMap.put("language", "zho");
        hashMap.put("reqId", data);
        hashMap.put("sid", sid);
        hashMap.put("action", "risk.captcha.init");
        hashMap.put("systemCode", "64");
        hashMap.put("version", "6.73.0");
        hashMap.put("token", token);
        hashMap.put("clientId", "");
        hashMap.put("ticket", ticket);

        String encrypt = null;
        try {

            encrypt = Demo.encrypt(JSONObject.toJSONString(hashMap));
        } catch (Exception e) {
            e.printStackTrace();
        }
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(mediaType, encrypt);
        // 创建请求对象，并添加自定义的请求头
        Request request = new Request.Builder()
                .url("https://marketingapi.hellobike.com/api")
                .post(body)
                .addHeader("Host", "api.hellobike.com")
                .addHeader("sid", sid)
                .addHeader("user-agent", "")
                .addHeader("inner_action", "risk.captcha.init")
                .addHeader("systemcode", "64")
                .addHeader("chaos", "true")
                .addHeader("content-type", "application/json; charset=UTF-8")
                .build();
        // 发送请求并获取响应
        Response response = null;
        try {
            response = client.newCall(request).execute();
            // 解密原文
            String decrypt = Demo.decrypt(response.body().string());
            JSONObject jsonObject = JSONObject.parseObject(decrypt);
            String string = jsonObject.getString("data");
            JSONObject dataJson = JSONObject.parseObject(string);
            if (dataJson == null)
                return null;
            String challenge = dataJson.getString("challenge");
            String captchaId = dataJson.getString("captchaId");
            HashMap<String, String> resutMap = new HashMap<>();
            resutMap.put("challenge", challenge);
            resutMap.put("captchaId", captchaId);
            return resutMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static String callBack(HashMap<String, String> dataMap, String sid) {
        System.out.println("回调的sid是:" + sid);
        OkHttpClient client = new OkHttpClient();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("capToken", dataMap.get("capToken"));
        hashMap.put("captchaOutput", dataMap.get("captcha_output"));
        hashMap.put("challenge", dataMap.get("challenge"));
        hashMap.put("genTime", dataMap.get("gen_time"));
        hashMap.put("lotNumber", dataMap.get("lot_number"));
        hashMap.put("passToken", dataMap.get("pass_token"));
        hashMap.put("reqId", dataMap.get("reqId"));
        hashMap.put("riskType", "");
        hashMap.put("sid", sid);
        hashMap.put("systemCode", "62");
        hashMap.put("action", "risk.captcha.check");
        hashMap.put("version", "6.73.0");
        hashMap.put("token", dataMap.get("capToken"));
        hashMap.put("clientId", "");
        hashMap.put("ticket", dataMap.get("ticket"));
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        String encrypt;
        try {
            encrypt = Demo.encrypt(JSONObject.toJSONString(hashMap));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        RequestBody body = RequestBody.create(mediaType, encrypt);
        // 创建请求对象，并添加自定义的请求头
        Request request = new Request.Builder()
                .url("https://marketingapi.hellobike.com/api")
                .post(body)
                .addHeader("Host", "api.hellobike.com")
                .addHeader("sid", sid)
                .addHeader("user-agent", "")
                .addHeader("inner_action", "risk.captcha.check")
                .addHeader("systemcode", "62")
                .addHeader("chaos", "true")
                .addHeader("content-type", "application/json; charset=UTF-8")
                .addHeader("accept-encoding", "accept-encoding")
                .build();
        // 发送请求并获取响应
        Response response = null;
        try {
            response = client.newCall(request).execute();
            // 解密原文
            String decrypt = Demo.decrypt(response.body().string());
            JSONObject jsonObject = JSONObject.parseObject(decrypt);
            System.out.println("jsonObject = " + jsonObject);
            String msg = jsonObject.getString("msg");
            String success = jsonObject.getString("data");
            JSONObject successData = JSONObject.parseObject(success);
            System.out.println(Constant.format.format(new Date()) + ":" + jsonObject);
            if (msg.equals("ok") && successData.getString("success").equals("1")) {
                System.out.println("处理图形验证成功");
                return "处理图形验证成功";
            }
            System.out.println("处理图形验证失败");
            return "处理图形验证失败";
        } catch (Exception e) {
            configureTasks();
        }
        System.out.println("处理图形验证失败");
        return "处理图形验证失败";
    }


    public static HashMap<String, String> getCodePostBL(String id,String proxy,JSONObject json) {
        OkHttpClient client = new OkHttpClient();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("captcha_id", id);
        hashMap.put("proxy", proxy);
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, JSONObject.toJSONString(hashMap));
        // 创建请求对象，并添加自定义的请求头
        Request request = new Request.Builder()
                .url(json.getString("server1"))
                .post(body)
                .build();
        // 发送请求并获取响应
        Response response = null;
        try {
            response = client.newCall(request).execute();
            // 解密原文
            JSONObject jsonObject = JSONObject.parseObject(response.body().string());
            JSONObject dataJson = jsonObject.getJSONObject("data");
            JSONObject seccode = JSONObject.parseObject(dataJson.getString("seccode"));
            String lotNumber = seccode.getString("lot_number");
            String passToken = seccode.getString("pass_token");
            String genTime = seccode.getString("gen_time");
            String captchaOutput = seccode.getString("captcha_output");
            // 封准需要的数据
            HashMap<String, String> codeData = new HashMap<>();
            codeData.put("captcha_output", captchaOutput);
            codeData.put("gen_time", genTime);
            codeData.put("lot_number", lotNumber);
            codeData.put("pass_token", passToken);
            return codeData;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private static String configureTasks() {
        String url = "http://103.36.167.125:81/hallo-api/initTxm";
        String result = null;
        try {
            result = HttpControllerUtil.doGet1(url);
        } catch (IOException e) {
            return null;
        }
        return result;
    }

    public static String txm(String ticket, String token, String reqId, String proxy, JSONObject fuck,String challenge,String captchaId,String sid) {
        if (Constant.NUMBER_BL > Constant.IP_SERVER.length) {
            Constant.NUMBER_BL = 0;
        }
        Constant.executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(4000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                Constant.isTxm = false;
            }
        });
        OkHttpClient client = new OkHttpClient();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("ticket", ticket);
        hashMap.put("token", token);
        hashMap.put("reqId", reqId);
        hashMap.put("SerUrl", "http://127.0.0.1:2000/SlideApi/JySlide");
        hashMap.put("proxy", proxy);
        hashMap.put("challenge", challenge);
        hashMap.put("captchaId", captchaId);
        hashMap.put("sid", sid);
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, JSONObject.toJSONString(hashMap));
        // 创建请求对象，并添加自定义的请求头
        Request request = new Request.Builder()
                .url(fuck.getString("address"))
                .post(body)
                .build();
        // 发送请求并获取响应
        Response response = null;
        Constant.NUMBER_BL++;
        try {
            response = client.newCall(request).execute();
            String string = response.body().string();
            if (string.equals("true")) {
                return "处理图形验证成功";
            } else {
                return "处理图形验证失败";
            }
        } catch (Exception e) {
            System.out.println("1");
        }
        System.out.println("处理图形验证失败");
        return "处理图形验证失败";
    }

    public static String txm2(String ticket, String token, String reqId, String proxy, JSONObject fuck) {
        if (Constant.NUMBER_BL > Constant.IP_SERVER.length) {
            Constant.NUMBER_BL = 0;
        }
        Constant.executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(4000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                Constant.isTxm = false;
            }
        });
        OkHttpClient client = new OkHttpClient();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("ticket", ticket);
        hashMap.put("token", token);
        hashMap.put("reqId", reqId);
        hashMap.put("SerUrl", "http://127.0.0.1:2000/SlideApi/JySlide");
        hashMap.put("ipAddress", proxy);
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, JSONObject.toJSONString(hashMap));
        // 创建请求对象，并添加自定义的请求头
        Request request = new Request.Builder()
                .url(fuck.getString("address2"))
                .post(body)
                .build();
        // 发送请求并获取响应
        Response response = null;
        Constant.NUMBER_BL++;
        try {
            response = client.newCall(request).execute();
            String string = response.body().string();
            if (string.equals("true")) {
                return "处理图形验证成功";
            } else {
                return "处理图形验证失败";
            }
        } catch (Exception e) {
            System.out.println("1");
        }
        System.out.println("处理图形验证失败");
        return "处理图形验证失败";
    }


    private static String configureTasks2() {
        String url = "http://api1.ydaili.cn/tools/MeasureApi.ashx?action=EAPI&secret=D5C9B1FA57EF5B3897BD51EEC9F440707F10281F1653D0C80178F447029E5526B57E95DB97FBA866&number=1&orderId=SH20241029181517960&format=txt";
        String result = null;
        try {
            result = HttpControllerUtil.doGet1(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (result != null) {
            return result;
        } else {
           return null;
        }
    }


    public static void demo(String encrypt,String token,String ticket,JSONObject fuck) {
        Constant.executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(4000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                Constant.isTxm = false;
            }
        });

        String proxy = configureTasks2();
        if (proxy == null)
            return;
        proxy = proxy.replaceAll("\\r\\n","");
        // 使用代理ip请求 避免踢码
        String[] split = proxy.split(":");
        Proxy proxys = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(split[0], Integer.valueOf(split[1])));

        OkHttpClient client = new OkHttpClient().newBuilder()
                .followRedirects(false)
                .followSslRedirects(false)
                .connectTimeout(5, TimeUnit.SECONDS)
                .readTimeout(5, TimeUnit.SECONDS)
                .proxy(proxys)
                .connectionPool(new ConnectionPool(5, 1, TimeUnit.SECONDS))
                .build();

        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, encrypt);
        // 创建请求对象，并添加自定义的请求头
        Request request = new Request.Builder()
                .url("https://taxiapi.hellobike.com/api")
                .post(body)
                .addHeader("Host", "taxiapi.hellobike.com")
                .addHeader("Connection", "keep-alive")
                .addHeader("content-type", "application/json; charset=UTF-8")
                .addHeader("user-agent", "Mozilla/5.0 (Linux; Android 13; 23049RAD8C Build/TKQ1.221114.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/127.0.6533.103 Mobile Safari/537.36")
                .addHeader("inner_action", "hitch.driver.journeyList")
                .addHeader("systemcode", "62")
                .addHeader("chaos", "true")
                .build();

        String finalProxy = proxy;
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                response = client.newCall(request).execute();
                assert response.body() != null;
                String decrypt = null;
                try {
                    decrypt = Demo.decrypt(response.body().string());
                    JSONObject jsonObjectOne = JSONObject.parseObject(decrypt);
                    System.out.println(jsonObjectOne);
                    String status = jsonObjectOne.getString("code");
                    if (status.equals("99")) {
                        JSONObject jsonObject = JSONObject.parseObject(jsonObjectOne.toString());
                        String data = jsonObject.getString("data");
                        MyHttpUtil.txm2(ticket,token,data, finalProxy,fuck);
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }

            }
        });
    }
}
